import { Component, OnInit, Input } from '@angular/core';
import { TreeNode } from 'primeng/primeng';
import { FormDesignService } from '../fb-design.service';
import { RouterModule, Routes, Router, ActivatedRoute, ParamMap } from '@angular/router';
import { MdlDialogService, MdlDialogReference, MdlSnackbarService } from '@angular-mdl/core';

@Component({
  selector: 'fb-print',
  templateUrl: './fb-print.component.html',
  styleUrls: ['./fb-print.component.scss'],
  providers: [FormDesignService]
})
export class FormPrintComponent implements OnInit {

  selectedNode: TreeNode;
  formTree: TreeNode[];
  loading: boolean = true;
  formName: string = '';
  formIdValue: number = 0;

  @Input()
  set formId(formId: number) {
    if (!formId) return;
    this.formIdValue = formId;
    this.render();
  }

  get formId(): number {
    return this.formIdValue;
  }

  constructor(
    private formDesignService: FormDesignService) { }

  ngOnInit() { }

  /**渲染PDF */
  render() {
    this.formDesignService.loadPrintFormContent(this.formIdValue).subscribe(data => {
      var pdfData = atob(data.fileContent); //$.base64.
      var uint8Array = new Uint8Array(pdfData.length);
      for (var i = 0; i < pdfData.length; i++) {
        uint8Array[i] = pdfData.charCodeAt(i);
      }
      this.formName = data.fileName;
      window['printPdfContent'] = { 'fileName': data.pdfName, 'pdfContent': uint8Array };
      $("#pdfConcent").attr("src", "/assets/other/pdfjs/viewer.html").ready();
    });
  }

  /** 文件上传 */
  onFileUpload(event, file) {
    const formData: FormData = new FormData();
    formData.append('file', event.files[0], event.files[0].name);
    this.formDesignService.uploadPrintTemplate(formData, this.formIdValue).subscribe(data => {
      this.render();
      file.clear();
    });
  }

  /** 文件下载 */
  download() {
    this.formDesignService.downloadPrintTemplate(this.formName, this.formIdValue).subscribe();
  }

}
